<template>
  <div class="subpage bind-card-container">
      <ul class="bind-card-info">
          <li>
              <div class="tag-name">用户名</div>
              <div class="tag-info">{{name}}</div>
          </li>
      </ul>
      <ul class="bind-card-info">
          <li>
              <div class="tag-name">银行卡号</div>
              <div class="tag-info">
                  <input type="tel" placeholder="请输入您的银行卡号" maxlength="19" v-model="bankCardNo" @blur="bankCardNoBlur()">
              </div>
          </li>
          <li>
              <div class="tag-name">银行名称</div>
              <div class="tag-info">
                  <img :src="bankImg" alt="" v-show="bankName">
                  <span class="color-gray" v-show="!bankName">根据银行卡号自动匹配</span>
              </div>
          </li>
          <li>
              <div class="tag-name">银行支行</div>
              <div class="tag-info">
                  <input type="text" placeholder="请输入银行支行" v-model="bankSub" @keyup="bankSubFn">
              </div>
          </li>
          <li>
              <div class="tag-name">手机号码</div>
              <div class="tag-info">{{showPhone}}</div>
          </li>
          <li>
              <div class="tag-name">验证码</div>
              <div class="tag-info">
                    <input type="tel" class="auth-code" placeholder="请输入验证码" maxlength="4" v-model="authCode">
                    <button class="u-send-msg-btn" v-if="!sendMsgFlag" @click="sendMsg" :disabled="sendMsgFlag">{{sendBtnText}}</button>
                    <span class="times color-primary" v-if="sendMsgFlag">{{times}}</span>
              </div>
          </li>
      </ul>
      <div class="bind-card-botttom">
          <van-button round class="u-btn-default u-bg-gradient-light" @click="addBankCard()">添加银行卡</van-button>
          <div class="bind-card-tips">
              <p>温馨提示</p>
              <p>
                  <span>1、</span>
                  <span>暂不支持信用卡；</span>
              </p>
              <p>
                  <span>2、</span>
                  <span>实名认证的姓名必须和绑定银行卡号开户名一致，否则无法提现</span>
              </p>
          </div>
      </div>
  </div>
</template>

<script>
import axios from 'axios';
import { Dialog } from 'vant';
import bankNameArr from '@/assets/js/bankname';
export default {
    components:{
        [Dialog.name]:Dialog
    },
    data() {
        return {
            name: '',
            bankCardNo: '',
            bankName: '',
            bankSub: '',
            bankImg: '',
            phone: '',
            showPhone: '',
            authCode: '', //验证码
            sendMsgFlag: false, //发送验证码状态
            sendBtnText: '发送验证码', //验证码文字
            times: '60s', //倒计时文字
        }
    },
    created() {
        this.name = this.$store.getters.userInfo.userName ? this.$store.getters.userInfo.userName : this.$store.getters.userInfo.nickName;
        let userPhone = this.$store.getters.userInfo.phone;
        this.phone = userPhone;
        this.showPhone = userPhone.substr(0, 3) + '****' + userPhone.substr(7);
    },
    mounted() {
        this.$tool.addEventListenerInputFocusout()
    },
    methods: {
        bankSubFn() {
            //只能输入中英文数字
            this.bankSub = this.bankSub.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g, '')
        },
        sendMsg() { //发送验证码
            if(!this.$tool.validator.isEmpty(this.bankCardNo)){
                this.$tool.toast('请输入您的银行卡号')
                return;
            }

            if(!this.$tool.validator.isEmpty(this.bankName)){
                this.$tool.toast('请输入正确的银行卡号')
                return;
            }

            if(!this.$tool.validator.isEmpty(this.bankSub)){
                this.$tool.toast('请输入银行支行')
                return;
            }

            if(!this.$tool.validator.isEmpty(this.phone)){
                this.$tool.toast('请输入手机号')
                return;
            }

            if(!this.$tool.validator.isMobilePhone(this.phone)){ 
                this.$tool.toast('请输入正确的手机号')
                return; 
            }
            this.sendMsgAjax()
        },

        sendMsgAjax() {
            let postData = {
                phone: this.phone,
                smsType: 4
            }
            this.$api.post('/api/sms/send_sms', postData)
                .then((res) => {
                    this.sendMsgFlag = true;
                    this.countdown();
                })
        },

        countdown() { //倒计时
            let time = 60;
            let t = setInterval(() => {
                time--;
                this.times = `${time}s`;
                if(time <= 0){
                    clearInterval(t)
                    this.sendBtnText = '重新获取';
                    this.sendMsgFlag = false;
                    this.times = '60s';
                }
            }, 1000)
        },

        addBankCard() { //添加银行卡
            if(!this.$tool.validator.isEmpty(this.bankCardNo)){
                this.$tool.toast('请输入您的银行卡号')
                return;
            }
            if(!this.$tool.validator.isEmpty(this.bankName)){
                this.$tool.toast('请输入正确的银行卡号')
                return;
            }
            if(!this.$tool.validator.isEmpty(this.bankSub)){
                this.$tool.toast('请输入银行支行')
                return;
            }
            if(!this.$tool.validator.isEmpty(this.authCode)){
                this.$tool.toast('请输入验证码')
                return;
            }
            if(!this.$tool.validator.isMsgCode(this.authCode)){
                this.$tool.toast('请输入4位数字验证码')
                return;
            }

            this.addBankCardAjax()
        },

        addBankCardAjax() { //添加银行卡请求
            let postData = {
                userName: this.name,
                cardNumber: this.bankCardNo,
                bankName: this.bankName,
                bankSub: this.bankSub,
                smsCode: this.authCode
            }
            this.$api.post('/api/user/setBankCard', postData)
                .then((res) => {
                    this.$api.get('/api/user/detail?noLoading')
                        .then((res) => {
                            res.data.bankName = this.bankName;
                            res.data.cardNumber = this.bankCardNo;
                            this.$store.commit("setUserInfo", res.data);
                        })
                    this.$tool.toast('绑定成功', 800);
                    setTimeout(() => {
                        this.$router.back()
                    }, 1000);
                })
        },

        bankCardNoBlur() { //银行卡号输入框失焦
            if(this.bankCardNo){
               this.matchingBank() 
            }
        },

        matchingBank() { //匹配银行
            let ajaxUrl = `https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?cardNo=${this.bankCardNo}&cardBinCheck=true`
            axios.get(ajaxUrl)
                .then((res) => {
                    if(res.data.cardType == 'CC'){
                        this.uDialog()
                        return;
                    }
                    if(res.data.validated){
                        this.bankName = bankNameArr[res.data.bank];
                        this.bankImg = 'https://apimg.alipay.com/combo.png?d=cashier&t=' + res.data.bank;
                    }else{
                        this.$tool.toast('请输入正确的银行卡号')
                        this.bankName = '';
                    }
                })
                .catch((err) => {
                    console.log('err:',err)
                })
        },

        uDialog() { //确认提示框
            Dialog.alert({
                title: '提示',
                message: '暂不支持信用卡绑定，请绑定储蓄卡'
            }).then(() => {
                this.bankCardNo = '';
            });
        }
    }
}
</script>

<style lang="scss" scoped>
    .bind-card-container {
        .bind-card-info {
            width: 100%;
            margin-bottom: 10px;
            background-color: #fff;
            li {
                display: flex;
                justify-content: space-between;
                align-items: center;
                width: 100%;
                padding: 20px 16px;
                box-sizing: border-box;
                border-bottom: 1px solid #F2F2F2;
                overflow: hidden;
                .tag-name {
                    font-size: 16px;
                }
                .tag-info {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    width: 224px;
                    font-size: 16px;
                    input {
                        padding: 0;
                        flex: 1;
                        font-size: 16px;
                        outline: none;
                        border: none;
                        background-color: #fff;
                    }
                    .auth-code {
                        width: 40px;
                    }
                }
            }
            li:last-child {
                border-bottom: none;
            }
        }
        .bind-card-botttom {
            width: 100%;
            padding: 0 16px;
            box-sizing: border-box;
            margin-top: 22px;
            .bind-card-tips {
                margin-top: 33px;
                p {
                    display: flex;
                    line-height: 22px;
                    color: #969C9E;
                    span {
                        display: block;
                    }
                }
                p:first-child {
                    margin-bottom: 10px;
                }
            }
        }
    }
</style>